/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-04-12
 * Time: 9:09
 */
public class Test2 {
    public static void main(String[] args) {
        Cat cat = new Cat("柚子","雌",2);
        Dog dog = new Dog("球球","雄",1);
        Bird bird = new Bird("泡芙","雌",2);

        //向上转型
        Animal animal = cat;
        animal.eat();
        animal = dog;
        animal.eat();
        animal = bird;
        animal.eat();
        //不能调用子类特有的方法
        //以下编译均会报错
        //a1.meow();
        //a2.bark();
        //a3.chirp();

        //向下转型
        //程序可以通过编程但是会抛出异常,animal实际指向的是鸟,但现在强制还原为猫,无法还原
        //cat = (Cat)animal;
        //cat.meow();

        //animal指向的是鸟,将animal还原为鸟是安全的
        bird = (Bird)animal;
        bird.chirp();

        //instanceof 判断它左边的对象是否是它右边的类的实例,返回boolean的数据类型,是返回true否则返回false;
        if(animal instanceof Cat) {
            cat = (Cat)animal;
            cat.meow();
        }

        if(animal instanceof Dog) {
            dog = (Dog)animal;
            dog.bark();
        }
        //animal指向的是鸟,左边的对象animal是右边鸟类的实例,为true,执行if内容语句
        if(animal instanceof Bird) {
            bird = (Bird) animal;
            bird.chirp();
        }
    }
}
